<style>
    .code{
        font-size: 14px;
        min-width:230px;
    }
    .CodeMirror-linewidget {
        position: absolute !important;
        top: 0;
        right: 1px!important;
        left: auto!important;
        z-index: 99;
        width: 25px!important;
        height: 23px!important;
        padding-left: 0!important;
        overflow: hidden!important;
        line-height: 23px;
        text-align: center;
        cursor: pointer;
    }
    .ivu-collapse{
        border: none !important;
        background-color: none !important;
    }
    .ivu-collapse>.ivu-collapse-item{
        margin-bottom: 10px;
        border: none !important;
        border-top:none !important;
        background-color: #fff;
    }
    .ivu-collapse>.ivu-collapse-item>.ivu-collapse-header{
        border-bottom: 1px solid #f5f5f5;
    }
    .ivu-collapse-content>.ivu-collapse-content-box{
        padding-top: 0 !important;
    }
    .radiusBox{
        margin-top: 10px;
        height: 26px;
        line-height: 26px;
    }
    .element1{
        width: 20px;
        height: 20px;
        background-color: #666;
        border-radius: 50%;
        float: left;
        margin-right: 10px;
        margin-top: 3px;
    }
    .radiusBox:first-child .element1 .child1{
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: #666;
        position: relative;
        top: 5px;
        left: 5px;
    }
    .child1{
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: #fff;
        position: relative;
        top: 5px;
        left: 5px;
    }
    .ivu-timeline-item{
        padding:0 !important;
    }
    .codemirror-box .ivu-btn-ghost{
        color:#515a6e;
    }
</style>
<template>
    <div class="search-wrap codemirror-box">
         <!-- 面包屑区域 -->
		<Breadcrumb class="bread-title">
            <BreadcrumbItem >物流跟踪详情</BreadcrumbItem>
        </Breadcrumb>

        <aside class='search-btn'>
            <ButtonGroup>
                <Button size='large'  v-for="(item,index) in btnsearch" :key="index" :type="formData.IN_trackingStatus===item.value?'primary':'ghost'" @click="handleBtn('IN_trackingStatus',item.value)">{{item.label}}<span class="number" >{{spanNumData[item.spanKey] || 0}}</span></Button>
            </ButtonGroup>
        </aside>
        <Alert type="success" class="text-center" >共查询到 {{trackDetailList.length}} 条数据</Alert>
        <div class="clearfix">
            <Row>
                <Col span="19">
                    <div style="height:1px;width:100%;padding-right:10px;blackground:#fff" >
                        <Collapse simple v-if="trackDetailList.length>0">
                            <Panel v-for="(item,index) in trackDetailList" :name="item.trackingCode" :key="index">
                                {{item.trackingCode}}
                                <template #content>
                                    {{item.trackingCode}}&nbsp;&nbsp;&nbsp;&nbsp;
                                    {{item.carrier ||'--'}}&nbsp;&nbsp;&nbsp;&nbsp;
                                    {{item.trackDetail?JSON.parse(item.trackDetail)[0].city:'--'}},{{item.trackDetail?JSON.parse(item.trackDetail)[0].state:'--'}},
                                    {{item.trackDetail?JSON.parse(item.trackDetail)[0].country:'--'}},{{item.trackDetail?JSON.parse(item.trackDetail)[0].status:'--'}},{{item.trackDetail?JSON.parse(item.trackDetail)[0].statusDetail:'--'}}
                                    <Timeline v-if="item.trackDetail">
                                        <TimelineItem v-for="(item1,index1) in JSON.parse(item.trackDetail)" :key="index1">{{item1.datetime}}&nbsp;&nbsp;{{item1.city ||'--'}},{{item1.state ||'--'}},{{item1.country ||'--'}},{{item1.message ||'--'}}</TimelineItem>
                                    </Timeline>
                                </template>
                            </Panel>
                        </Collapse>
                    </div>
                </Col>
            
                <Col span="5">
                    <!-- 利用组件 -->
                    <Codemirror
                        ref="myCm"
                        :value="curCode"
                        v-model:value="msg"
                        :options="cmOptions"
                        placeholder="每行输入一个单号，最多只允许输入40个单号。"
                        @changes="changes"
                        @ready="ready"
                        @focus="focusclear"
                        class="code"
                    ></Codemirror>
                    <div class="text-right margin-top-10">
                        <Button type="primary" @click="submit">查询</Button>
                        <Button class="margin-left-10" @click="clearAll">重置</Button>
                    </div>
                </Col>
            </Row>
        </div>
    </div>
</template>



<script >
import { ref, onMounted } from 'vue'
import Codemirror, { CmComponentRef } from "codemirror-editor-vue3";

// language
import "codemirror/mode/javascript/javascript.js";

import { HttpSearchTracking, HttpSearchManageTracking, HttpGetCountByStatusNum,HttpGetCountManageByStatusNum } from "@/service/api/views";


export default {
    data(){
        return {
            type: this.$route.query.type,
            curCode:'每行输入一个单号，最多只允许输入40个单号。',
            msg:'',
            widgets:[],
            cmOptions:{
                value:'',
                mode:"text/html",
                theme: "foo bar",
                lineNumbers:true,
                lineWrapping: true,
                showCursorWhenSelecting:true,
                readOnly:false,
                lineWidgets:true,
                autoRefresh: true, // 自动刷新
                lineNumberFormatter: function (line) {return line + ".";},  // 自定义行数格式内容
                viewportMargin: Infinity,
                extensions:[],
            },
            btnsearch: [{
                value: null,
                label: '所有',
                spanKey:'all',
            },{
                value: 'unknown',
                label: '初始化',
                spanKey:'unknown',
            },{
                value: 'pre_transit',
                label: '待发运',
                spanKey:'preTransit',
            } ,{
                value: 'in_transit',
                label: '在途',
                spanKey:'inTransit',
            },{
                value: 'out_for_delivery,available_for_pickup',
                label: '派送中',
                spanKey:'outForDelivery',
            },{
                value: 'delivered',
                label: '已妥投',
                spanKey:'delivered',
            },{
                value: 'failure,error',
                label: '异常',
                spanKey:'error',
            },{
                value: 'cancelled',
                label: '已取消',
                spanKey:'cancelled',
            },{
                value: 'return_to_sender',
                label: '已退回',
                spanKey:'back',
            }],
            formData: {
                IN_trackingStatus: null,
            },
            flag:0,
            trackDetailList:[],
            showNumRows:false,
            spanNumData:{},
        }
    },
    components:{
        Codemirror
    },
    methods:{
        ready(val){
            var trackList = this.$route.query.trackNo;
            if(!trackList) return
            let strNo = trackList.replace(/,/g,'\n')
            val.setValue(strNo);
            this.submit();
        },
        focusclear(){
            var trackList = this.$route.query.trackNo;
            if(trackList) return
            this.curCode = ''
        },
        // 切换头部tab
        handleBtn(key, val){
            
            this.formData[key] = val
            this.submit();
        },
        changes(val){
            // 此处用来判断输入内容，然后加入删除按钮
            let waiting = null;
            
            clearTimeout(waiting);
            waiting = setTimeout(this.updateHints(val), 50);
            
        },
        updateHints(editor){

            var _this = this;
            var text = this.msg;
            var lines = this.msg.split("\n");
            var info,after;

            // Codemirror内部缓存更改，只有在完成某些操作后才更新其DOM结构
            editor.operation(function(){
                
                // 清空所有删除按钮
                for (var i = 0; i < _this.widgets.length; ++i) {
                    editor.removeLineWidget(_this.widgets[i]);
                }
                _this.widgets.length = 0;

                // 重新根据输入内容的数组生成删除按钮
                if(text) {
                    for (var j = 0; j < lines.length; ++j) {
                        var dom = _this.createClearBox(editor,j);
                        var widget = editor.addLineWidget(j, dom, {coverGutter: false, noHScroll: true});
                        // console.log(widget,'widget')
                        _this.widgets.push(widget);
                    }
                }
            });
            // Codemirror.refresh;
            // 返回clinetWidth/clientHeight、width/height、left/top的相关结果
            info = editor.getScrollInfo();
            // editor.getCursor() 定位当前光标的行（line）和字符长度（ch）,结果返回 {line,ch}
            // editor.charCoords() 返回字符所在行的位置和尺寸，eg：第1行：{bottom: 40,left: 4,right: 4,top: 4} 第2行：{bottom: 93,left: 4,right: 4,top: 57}
            after = editor.charCoords({line: editor.getCursor().line + 1, ch: 0}, "local").top;

            // eg : top = 8, top是根据输入行，动态变化。clientHeight:178
            if (info.top + info.clientHeight < after) {
                editor.scrollTo(null, after - info.clientHeight + 18);
            }
        },
        createClearBox(editor,i){
            var node,iDom;

            node = document.createElement("a");
            node.style = "display:block";
            node.setAttribute("href","javascript:void(0)");
            node.setAttribute("yqi-data-index",i);
            node.setAttribute("yqg-events","{C:功能操作,A:全局-单行删除单号}");
            node.setAttribute("title","删除");

            iDom = node.appendChild(document.createElement("i"));
            iDom.className = "ivu-icon ivu-icon-md-close-circle";

             //创建的元素绑定删除事件，并处理删除每行后的光标及滚动位置调整处理
            node.onclick = function() {
                var index = this.getAttribute("yqi-data-index");
                var topScroll = -1;

                if (index !== null) {
                    index -= 0;
                    var text = editor.getValue();
                    var lines = text.split("\n");

                    // 如果是第一行，将删除输入内容数组的第一行,并改变数组长度
                    if (index === 0) {
                        lines.shift();
                    }
                    // 如果当前删除按钮的索引值等于（输入内容数组长度 - 1），则删除数组最后一项，并自减索引值和修改数组长度
                    else if (i === lines.length - 1) {
                        lines.pop();
                        index--;
                    }
                    else {
                        var r = lines.slice(0, index);
                        var n = lines.slice(index + 1);

                        lines = r.concat(n)

                        var info = editor.getScrollInfo();
                        topScroll = info.top;
                    }

                    editor.setValue(lines.join("\n"));
                    editor.setCursor(index, editor.getLine(index).length);
                    if (topScroll > -1){
                        editor.scrollTo(null, topScroll);
                    }
                }
                editor.focus();
            };
            return node;
        },
        clearAll(){
            // // 回归焦点
            this.curCode = '';
            this.msg = '';
            this.trackDetailList = [];
            this.spanNumData = {}
        },
        submit(){
            let arrlist = [],trackingCodes = [];
            arrlist = this.msg.split('\n')
            arrlist.map(item=>{
                if(item){
                    trackingCodes.push(item)
                }
            })
            if(this.type=='manage'){
                
                HttpSearchManageTracking({
                    trackingCodes:trackingCodes,
                    trackingStatus:this.formData.IN_trackingStatus,
                }).then(res=>{
                    this.trackDetailList = res.data;
                },err=>{
                    this.$Message.error(err.message)
                })
                HttpGetCountManageByStatusNum({
                    trackingCodes:trackingCodes
                }).then(res=>{
                    this.spanNumData = res.data
                    this.flag = 1
                },err=>{
                    this.$Message.error(err.message)
                })
            }else{
                HttpSearchTracking({
                    trackingCodes:trackingCodes,
                    trackingStatus:this.formData.IN_trackingStatus,
                }).then(res=>{
                    this.trackDetailList = res.data;
                },err=>{
                    this.$Message.error(err.message)
                })
                HttpGetCountByStatusNum({
                    trackingCodes:trackingCodes
                }).then(res=>{
                    this.spanNumData = res.data
                    this.flag = 1
                },err=>{
                    this.$Message.error(err.message)
                })
            }
        }

    },
}


</script>